package com.yc.service.impl;

import com.yc.service.SendMailService;
import com.yc.util.ValidateCodeUtils;
import com.yc.vo.Result;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class SendMailServiceImpl implements SendMailService {

    private String code;

    private Date sendTime;

    /**
     * 发送QQ验证码
     * @param sender
     * @param mailSender
     * @param receiver
     * @return
     */
    @Override
    @Async
    public Result sendMail(String sender, JavaMailSenderImpl mailSender, String receiver) {
        Result result = new Result();
        SimpleMailMessage message = new SimpleMailMessage();
        message.setSubject("双辞动漫验证码");//设置邮件标题
        code = ValidateCodeUtils.generateValidateCode(6).toString();
        System.out.println(code);
        sendTime = new Date();
        message.setText("尊敬的用户,您好:\n"
                + "\n本次请求的邮件验证码为:" + code + ",本验证码5分钟内有效，请及时输入。（请勿泄露此验证码）\n"
                + "\n如非本人操作，请忽略该邮件。\n(这是一封自动发送的邮件，请不要直接回复）");    //设置邮件正文
        message.setFrom(sender);//发件人
        message.setTo(receiver);//收件人
        mailSender.send(message);//发送邮件
        result.setCode(1);
        result.setMsg("发送验证码成功");
        return result;
    }

    /**
     * 验证码比对
     * @param verCode
     * @return
     */
    @Override
    public Result addUser(String verCode) {
        Result result = new Result();
        Date date = new Date();
        //判断验证码
        if ( ValidateCodeUtils.getMinute(sendTime, date) > 5) {
            result.setCode(0);
            result.setMsg("验证码已经失效！！！");
        }
        if (!verCode.equals(code)) {
            result.setCode(0);
            result.setMsg("验证码不正确！！！");
        }else{
            result.setCode(1);
        }
        return result;
    }
}
